package main

import (
	"encoding/gob"
	"fmt"
	"log"
	"os"
	"os/exec"
	"time"

	"honeybadgerbft/hbbft"
)

func main() {
	fmt.Println("Starting local HoneyBadger test...")

	// 注册gob类型
	registerGobTypes()

	// 启动4个节点
	nodes := []int{0, 1, 2, 3}
	processes := make([]*exec.Cmd, len(nodes))

	// 启动所有节点
	for i, nodeID := range nodes {
		addr := fmt.Sprintf("localhost:%d", 8000+i)
		peers := fmt.Sprintf("0:localhost:8000,1:localhost:8001,2:localhost:8002,3:localhost:8003")
		
		cmd := exec.Command("./honeybadger", 
			"-id", fmt.Sprintf("%d", nodeID),
			"-addr", addr,
			"-peers", peers,
			"-n", "4",
			"-f", "1",
			"-batch", "1000")
		
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		
		if err := cmd.Start(); err != nil {
			log.Fatalf("Failed to start node %d: %v", nodeID, err)
		}
		
		processes[i] = cmd
		fmt.Printf("Started node %d on %s\n", nodeID, addr)
	}

	// 等待一段时间让节点运行
	fmt.Println("Waiting for nodes to run...")
	time.Sleep(30 * time.Second)

	// 停止所有节点
	fmt.Println("Stopping all nodes...")
	for i, cmd := range processes {
		if cmd.Process != nil {
			cmd.Process.Kill()
			fmt.Printf("Stopped node %d\n", i)
		}
	}

	fmt.Println("Test completed!")
}

func registerGobTypes() {
	gob.Register(&hbbft.ACSMessage{})
	gob.Register(&hbbft.RBCMessage{})
	gob.Register(&hbbft.BBAMessage{})
	gob.Register(&hbbft.HBMessage{})
	gob.Register(&hbbft.BroadcastMessage{})
	gob.Register(&hbbft.AgreementMessage{})
	gob.Register(hbbft.SimpleTransaction(""))
}


